<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Wallpaper_private extends wsFrontend
{

    public function __construct()
    {
        parent::__construct();
        if (strpos(strtolower($this->uri->uri_string()), 'wallpaper_private') !== false) {
            redirect(base_url());
        }
        $this->db->cache_set_path(dirname($this->db->cachedir) . '/wallpaper_page/');
    }

    public function index($category_slug = '', $wallpaper_slug = '', $wallpaper_hash_id = '')
    {
        $data = array();

        if (!$category_slug && !$wallpaper_slug && !$wallpaper_hash_id)
            custom_404();

        $filter['category_slug'] = rawurldecode($category_slug);
        $filter['wallpaper_slug'] = $wallpaper_slug;
        $filter['wallpaper_hash'] = $wallpaper_hash_id;
        $this->load->model('wallpaper_model');
        $data['wallpaper'] = $this->wallpaper_model->get_wallpaper($filter);


        if (!$data['wallpaper'] && $wallpaper_hash_id) {
            $data['wallpaper'] = $this->wallpaper_model->get_wallpaper(array('wallpaper_hash' => $wallpaper_hash_id));
        }
        if (!$data['wallpaper']) {
            unset($filter['wallpaper_hash']);
            $data['wallpaper'] = $this->wallpaper_model->get_wallpaper($filter);
        }

        if (!$data['wallpaper'])
            custom_404();

        $data['search_replace'] = array(
            '{C_SLUG_FULL}' => $data['wallpaper']->cFullSlug,
            '{C_SLUG}' => $data['wallpaper']->category_slug,
            '{W_SLUG}' => $data['wallpaper']->wallpaper_slug,
            '{W_HASH}' => $data['wallpaper']->wallpaper_hash
        );
        $data['url'] = $this->route_links->build_link('wallpaper_page', $data['search_replace']);
        $data['facebook_cover_url'] = $this->route_links->build_link('wallpapers_page_cover_facebook', $data['search_replace']);
        if ($data['url'] != current_url())
            redirect($data['url']);


        if (!$this->config->item('facebook_comment')) {
            $this->load->helper('date');
        }

        $data['captcha'] = $data['captchaError'] = false;
        if ($this->config->item('enable_captcha') && !$this->user->is_loggedIn()) {
            $data['captcha'] = true;
        }

        //Force Turn off captcha
        //$data['captcha'] = false;

        $this->comment_submit($data);

        $data['comments'] = $data['comment_count'] = false;
        if (!$this->config->item('facebook_comment')) {
            $comment_db = array(
                'wallpaper_hash' => $data['wallpaper']->wallpaper_hash,
                'per_page' => $this->config->item('comment_limit'),
                'offset' => 0,
            );
            $data['comments'] = $this->wallpaper_model->get_comments($comment_db);
            $data['comment_count'] = $this->wallpaper_model->get_comments($comment_db + array('count' => true));
        }


        $this->tpl->active_category = explode('/', $data['wallpaper']->cFullSlug);


        $cFullSlug = explode('/', $data['wallpaper']->cFullSlug);
        $cFullName = explode('|', $data['wallpaper']->cFullName);
        $appendSlug = '';

        $this->tpl->breadcrumbs['壁纸分类'] = base_url($this->route_links->get('category_page_index'));
        foreach ($cFullSlug as $k => $cSlug) {
            if ($appendSlug)
                $appendSlug .= '/';
            $category_slug_build = $this->route_links->build_link('category_page', array(
                '{C_SLUG_FULL}' => $appendSlug . $cSlug
            ));
            $this->tpl->breadcrumbs[(isset($cFullName[$k]) ? $cFullName[$k] : $k)] = $category_slug_build;
            $appendSlug .= $cSlug;
        }
        $this->tpl->breadcrumbs[$data['wallpaper']->wallpaper_name] = 'active';

        $this->db->custom_seqgment('resolution', 'index');
        $this->load->model('resolution_model');
        $data['resolutions'] = $this->frontend_helper->resolutions_grouping($this->resolution_model->get_AllResolutions());
        $this->db->reset_custom_seqgment();

        $data['previous_next'] = $this->wallpaper_model->previousNext($data['wallpaper']->wallpaper_seq_id);

        $this->insert_view($data['wallpaper']->wallpaper_seq_id);

        $data['favourite'] = false;
        if ($this->user->is_loggedIn()) {
            $data['favourite'] = $this->wallpaper_model->is_userAddedToFavourite($data['wallpaper']->wallpaper_seq_id, $this->user->get_id());
        }

        $data['colors'] = $this->wallpaper_model->get_colors($data['wallpaper']->wallpaper_seq_id);

        $data['related_wallpapers'] = $this->wallpaper_model->getWallpapers(array(
            'per_page' => $this->config->item('related_wallpaper_limit'),
            'category' => $data['wallpaper']->category_seq_id,
            'wallpaper_id_not' => array($data['wallpaper']->wallpaper_seq_id),
            'keyword_related' => $data['wallpaper']->wallpaper_name
        ));


        $search_replace = array(
            '{WALL_NAME}' => $data['wallpaper']->wallpaper_name,
            '{WALL_CAT_NAME}' => $data['wallpaper']->category_name,
            '{WALL_TAGS}' => $data['wallpaper']->tags
        );
        if ($data['wallpaper']->wallpaper_metatitle)
            $this->tpl->meta ['title'] = $data['wallpaper']->wallpaper_metatitle;
        else
            $this->tpl->meta ['title'] = $this->metadata->get_metadata('_wallpaper_index_title', 'wallpaper_page', $search_replace);

        if ($data['wallpaper']->wallpaper_metadescription)
            $this->tpl->meta ['description'] = $data['wallpaper']->wallpaper_metadescription;
        else
            $this->tpl->meta ['description'] = $this->metadata->get_metadata('_wallpaper_index_description', 'wallpaper_page', $search_replace);

        if ($data['wallpaper']->wallpaper_metakeywords)
            $this->tpl->meta ['keywords'] = $data['wallpaper']->wallpaper_metakeywords;
        else
            $this->tpl->meta ['keywords'] = $this->metadata->get_metadata('_wallpaper_index_keywords', 'wallpaper_page', $search_replace);


        $this->tpl->contents [] = $this->tpl->fetch('contents/wallpaper_single', $data, true);
        $this->tpl->render('layouts/home');
    }

    public function preview($category_slug = '', $wallpaper_slug = '', $wallpaper_hash_id = '', $width = false, $Height = false, $download = false)
    {
        if (!$category_slug && !$wallpaper_slug && !$wallpaper_hash_id)
            custom_404();

        $filter['category_slug'] = rawurldecode($category_slug);
        $filter['wallpaper_slug'] = $wallpaper_slug;
        $filter['wallpaper_hash'] = $wallpaper_hash_id;
        $this->load->model('wallpaper_model');
        $data['wallpaper'] = $this->wallpaper_model->get_wallpaper($filter);

        @ini_set('memory_limit', '64M');

        if (!$data['wallpaper'] && $wallpaper_hash_id) {
            $data['wallpaper'] = $this->wallpaper_model->get_wallpaper(array('wallpaper_hash' => $wallpaper_hash_id));
        }
        if (!$data['wallpaper']) {
            unset($filter['wallpaper_hash']);
            $data['wallpaper'] = $this->wallpaper_model->get_wallpaper($filter);
        }

        if (!$data['wallpaper'])
            custom_404();
        $data['width'] = $width;
        $data['height'] = $Height;
        $data['search_replace'] = array(
            '{C_SLUG_FULL}' => $data['wallpaper']->cFullSlug,
            '{C_SLUG}' => $data['wallpaper']->category_slug,
            '{W_SLUG}' => $data['wallpaper']->wallpaper_slug,
            '{W_HASH}' => $data['wallpaper']->wallpaper_hash,
            '{R_WIDTH}' => $width,
            '{R_HEIGHT}' => $Height,
        );
        $data['url'] = $this->route_links->build_link('wallpaper_page', $data['search_replace']);
        $data['colors'] = $this->wallpaper_model->get_colors($data['wallpaper']->wallpaper_seq_id);

        if (!$width || !$Height)
            redirect($data['url']);

        if ($data['wallpaper']->wallpaper_width < $width || $data['wallpaper']->wallpaper_height < $Height) {
            $this->session->set_flashdata('FLASH_ERROR', $this->language->get_text('SRSBLTTAR', 'wallpaper'));
            redirect($data['url']);
        }


        if (!file_exists(ORIGINALS_FOLDER . DS . $data['wallpaper']->wallpaper_image_path)) {
            $this->session->set_flashdata('FLASH_ERROR', $this->language->get_text('sorry-original-image-doest-exists', 'wallpaper'));
            redirect($data['url']);
        }

        if ($download) {
            $data['image'] = $this->image_workshop->convert_resolution($data['wallpaper']->wallpaper_image_path, $data['wallpaper']->wallpaper_hash, $data['wallpaper']->wallpaper_date_created, $width, $Height, $data['wallpaper']->wallpaper_crop_position, true);
            $this->load->helper('download');
            $this->insert_download($data['wallpaper']->wallpaper_seq_id);
            force_download($data['image'], NULL);
        }

        $data['image'] = $this->image_workshop->convert_resolution($data['wallpaper']->wallpaper_image_path, $data['wallpaper']->wallpaper_hash, $data['wallpaper']->wallpaper_date_created, $width, $Height, $data['wallpaper']->wallpaper_crop_position);
        $this->insert_view($data['wallpaper']->wallpaper_seq_id);

        $search_replace = array(
            '{WALL_NAME}' => $data['wallpaper']->wallpaper_name,
            '{WALL_CAT_NAME}' => $data['wallpaper']->category_name,
            '{WALL_TAGS}' => $data['wallpaper']->tags,
            '{R_WIDTH}' => $width,
            '{R_HEIGHT}' => $Height,
        );
        if ($data['wallpaper']->wallpaper_metatitle)
            $this->tpl->meta ['title'] = $data['wallpaper']->wallpaper_metatitle;
        else
            $this->tpl->meta ['title'] = $this->metadata->get_metadata('_wallpaper_preview_title', 'wallpaper_page', $search_replace);

        if ($data['wallpaper']->wallpaper_metadescription)
            $this->tpl->meta ['description'] = $data['wallpaper']->wallpaper_metadescription;
        else
            $this->tpl->meta ['description'] = $this->metadata->get_metadata('_wallpaper_preview_description', 'wallpaper_page', $search_replace);

        if ($data['wallpaper']->wallpaper_metakeywords)
            $this->tpl->meta ['keywords'] = $data['wallpaper']->wallpaper_metakeywords;
        else
            $this->tpl->meta ['keywords'] = $this->metadata->get_metadata('_wallpaper_preview_keywords', 'wallpaper_page', $search_replace);


        $data['previous_next'] = $this->wallpaper_model->previousNext($data['wallpaper']->wallpaper_seq_id, $width, $Height);

        $this->tpl->contents [] = $this->tpl->fetch('contents/wallpaper_single_preview', $data, true);
        $this->tpl->render('layouts/empty');
    }

    private function comment_submit($data)
    {
        if (isset($_POST['submit_comment'])) {
            $return['captcha'] = $data['captcha'];
            $this->load->library('form_validation');
            if (!$this->user->is_loggedIn()) {
                $this->form_validation->set_rules('guest_name', $this->language->get_text('guest-name', 'comment'), 'required');
                $this->form_validation->set_rules('guest_email', $this->language->get_text('guest-email', 'comment'), 'required|valid_email');
                if ($data['captcha'])
                    $this->form_validation->set_rules('recaptcha_response_field', $this->language->get_text('captcha-code', 'account'), 'required');
            }
            $this->form_validation->set_rules('comment_text', $this->language->get_text('comment-text', 'comment'), 'required|min_length[4]');
            if ($this->form_validation->run()) {
                $has_error = false;
                if ($data['captcha']) {
                    $resp = recaptcha_check_answer('', $_SERVER["REMOTE_ADDR"], $this->input->post('recaptcha_challenge_field'), $this->input->post('recaptcha_response_field'));
                    if (!$resp->is_valid) {
                        $data['captchaError'] = $return['error'] = $resp->error;
                        $has_error = true;
                    }
                }

                if (!$has_error) {
                    $return['success'] = $this->language->get_text('your-comment-has-been-submitted', 'comment');
                    $insert_data = array(
                        'wallpaper_seq_id' => $data['wallpaper']->wallpaper_seq_id,
                        'comment_description' => strip_tags($this->input->post('comment_text')),
                        'comment_date' => date('Y-m-d H:i:s'),
                    );
                    if ($this->user->is_loggedIn()) {
                        $insert_data['user_seq_id'] = $this->user->get_id();
                        $insert_data['comment_status'] = 1;
                    } else {
                        $insert_data['guest_name'] = $this->input->post('guest_name');
                        $insert_data['guest_email'] = $this->input->post('guest_email');
                    }
                    $insert_id = $this->wallpaper_model->insert_comment($insert_data);
                    if ($this->input->is_ajax_request()) {
                        $comment_data = array('comment' => $this->wallpaper_model->get_single_commentBYID($insert_id));
                        $return['html'] = $this->tpl->fetch('contents/comment_single', $comment_data);
                    } else {
                        $this->session->set_flashdata('FLASH_MSG', $this->language->get_text('your-comment-has-been-submitted', 'comment') . ' ' . (!$this->user->is_loggedIn() ? $this->language->get_text('waiting-for-approval', 'comment') : ''));
                        redirect($data['url']);
                    }
                }
            } else {
                if ($this->input->is_ajax_request()) {
                    $return['error'] = validation_errors();
                }
            }

            if ($this->input->is_ajax_request()) {
                echo json_encode($return);
                exit;
            }
        }
    }

    private function insert_view($wallpaper_seq_id)
    {
        $ip = ip2long($this->input->ip_address());
        $search_log = array(
            'DATE(wv_date)' => date('Y-m-d'),
            'INET_NTOA(wv_ip)' => $ip ? $ip : '0.0.0.0',
            'wv_wid' => $wallpaper_seq_id
        );
        if ($this->user->is_loggedIn())
            $search_log['wv_uid'] = $this->user->get_id();
        $is_viewed = $this->wallpaper_model->is_viewed($search_log);

        if (!$is_viewed) {
            $insert_log = array(
                'wv_uid' => $this->user->get_id(),
                'wv_wid' => $wallpaper_seq_id,
                'wv_ip' => ip2long($this->input->ip_address()),
                'wv_date' => date('Y-m-d H:i:s')
            );
            $this->wallpaper_model->insert_view($insert_log);
        }
    }

    private function insert_download($wallpaper_seq_id)
    {
        $insert_log = array(
            'wd_uid' => $this->user->get_id(),
            'wd_wid' => $wallpaper_seq_id,
            'wd_ip' => ip2long($this->input->ip_address()),
            'wd_date' => date('Y-m-d H:i:s')
        );
        $this->wallpaper_model->insert_download($insert_log);
    }


    public function cover($category_slug = '', $wallpaper_slug = '', $wallpaper_hash_id = '', $type = false)
    {
        $allowed_type = array(
            'facebook'
        );
        if ((!$category_slug && !$wallpaper_slug && !$wallpaper_hash_id) || !in_array($type, $allowed_type))
            custom_404();

        $filter['category_slug'] = rawurldecode($category_slug);
        $filter['wallpaper_slug'] = $wallpaper_slug;
        $filter['wallpaper_hash'] = $wallpaper_hash_id;
        $this->load->model('wallpaper_model');
        $data['wallpaper'] = $this->wallpaper_model->get_wallpaper($filter);

        if (!$data['wallpaper'] && $wallpaper_hash_id) {
            $data['wallpaper'] = $this->wallpaper_model->get_wallpaper(array('wallpaper_hash' => $wallpaper_hash_id));
        }
        if (!$data['wallpaper']) {
            unset($filter['wallpaper_hash']);
            $data['wallpaper'] = $this->wallpaper_model->get_wallpaper($filter);
        }

        if (!$data['wallpaper'])
            custom_404();


        $data['search_replace'] = array(
            '{C_SLUG_FULL}' => $data['wallpaper']->cFullSlug,
            '{C_SLUG}' => $data['wallpaper']->category_slug,
            '{W_SLUG}' => $data['wallpaper']->wallpaper_slug,
            '{W_HASH}' => $data['wallpaper']->wallpaper_hash,
        );

        switch ($type) {
            case'facebook':
                $data['width'] = FB_WIDTH;
                $data['height'] = FB_HEIGHT;
                $data['slug'] = 'wallpapers_page_cover_facebook';
                break;
        }

        $data['type'] = $type;

        $data['url'] = $this->route_links->build_link($data['slug'], $data['search_replace']);
        $data['w_url'] = $this->route_links->build_link('wallpaper_page', $data['search_replace']);
        $data['colors'] = $this->wallpaper_model->get_colors($data['wallpaper']->wallpaper_seq_id);

        if ($data['url'] != current_url())
            redirect($data['url']);

        $data['previous_next'] = $this->wallpaper_model->previousNext($data['wallpaper']->wallpaper_seq_id, $data['width'], $data['height']);


        $search_replace = array(
            '{WALL_NAME}' => $data['wallpaper']->wallpaper_name,
            '{WALL_CAT_NAME}' => $data['wallpaper']->category_name,
            '{WALL_TAGS}' => $data['wallpaper']->tags
        );

        if ($data['wallpaper']->wallpaper_metatitle)
            $this->tpl->meta ['title'] = $data['wallpaper']->wallpaper_metatitle;
        else
            $this->tpl->meta ['title'] = $this->metadata->get_metadata('_wallpapers_page_facebook_title', 'wallpaper_page', $search_replace);

        if ($data['wallpaper']->wallpaper_metadescription)
            $this->tpl->meta ['description'] = $data['wallpaper']->wallpaper_metadescription;
        else
            $this->tpl->meta ['description'] = $this->metadata->get_metadata('_wallpapers_page_facebook_description', 'wallpaper_page', $search_replace);

        if ($data['wallpaper']->wallpaper_metakeywords)
            $this->tpl->meta ['keywords'] = $data['wallpaper']->wallpaper_metakeywords;
        else
            $this->tpl->meta ['keywords'] = $this->metadata->get_metadata('_wallpapers_page_facebook_keywords', 'wallpaper_page', $search_replace);

        $this->tpl->contents [] = $this->tpl->fetch('contents/wallpaper_single_cover', $data, true);
        $this->tpl->render('layouts/empty_nocontainer');
    }
}
